package com.multi.publicly.utils;

import com.multi.common.constant.CacheConstants;
import com.multi.common.core.domain.entity.BkTenantInfo;
import com.multi.common.core.redis.RedisCache;
import com.multi.common.utils.StringUtils;
import com.multi.common.utils.sign.Base64;
import com.multi.publicly.vo.LoginFormVo;
import com.multi.tenant.service.IBkTenantInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description 微信小程序工具类
 * @ClassName WxAppUtils
 * @Author pzj
 * @Data 2024/12/2 14:32
 */
@Slf4j
@Component
public class WxMiddleUtils {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WechatUtil wechatUtil;

    @Autowired
    private IBkTenantInfoService bkTenantInfoService;

    /**
     * 获取accessToken信息
     * @param bkTenantInfo
     * @return
     */
    @SneakyThrows
    public String obtainAccessToken(BkTenantInfo bkTenantInfo){
        String appId = new String(Base64.decode(bkTenantInfo.getTenantAppid()));
        String appSecret = new String(Base64.decode(bkTenantInfo.getTenantAppsecret()));
        String accessToken = redisCache.getCacheObject(CacheConstants.ACCESS_TOKEN+bkTenantInfo.getId());
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = wechatUtil.getAccessToken(appId, appSecret);
            redisCache.setCacheObject(CacheConstants.ACCESS_TOKEN+bkTenantInfo.getId(), accessToken, 1, TimeUnit.HOURS);
        }
        return accessToken;
    }

    /**
     * 获取电话信息
     * @param access_token
     * @param code
     * @return
     */
    @SneakyThrows
    public String obtainPhone(String access_token, String code) {
        return wechatUtil.getphoneByToken(access_token, code);
    }

    /**
     * 获取用户的openID
     * @param loginFormVo
     * @return
     */
    public String obtainOpenId(LoginFormVo loginFormVo) {
        //根据TenantId查询租户信息
        BkTenantInfo bkTenantInfo = bkTenantInfoService.selectBkTenantInfoById(loginFormVo.getTenantId());
        String tenantAppid = new String(Base64.decode(bkTenantInfo.getTenantAppid()));
        String tenantAppsecret = new String(Base64.decode(bkTenantInfo.getTenantAppsecret()));
        String code = loginFormVo.getCode();
        return wechatUtil.getOpenId(tenantAppid,tenantAppsecret,code);
    }
}
